<?php
/**
 * Created by PhpStorm.
 * User: wjj
 * Date: 2016/11/1
 */

namespace app\logic;


use app\common\HttpCurl;
use app\common\WxUtil;
use app\models\Device;
use app\models\Manager;
use app\models\Play;
use app\models\Shop;
use app\models\ShopPlay;
use app\models\ShopTag;
use yii;


class ShopLogic
{
    public static $input_type_list = ['下拉框','输入框','单选项','多选项'];

    public function getShop($query = [], $page = 1, $limit = 10)
    {
        $shop = Shop::find()->filterWhere($query)->orderBy('shop_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $shop->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $shop->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'shop/index',
                'query' => $query
            ]
        ];
        return $return;
    }

    public function getAllPlay($playids=0){
        if($playids){
            return Play::find()->where(['not in','play_id',$playids])->asArray()->all();
        }else{
            return Play::find()->asArray()->all();
        }

    }

    public function addShop($params,$uploadresult='')
    {
        $shop = new Shop();
        $shop->shop_no = $params['shop_no'];
        $shop->shop_name = $params['shop_name'];
        $shop->shop_parent_name = $params['shop_parent_name'];
        $shop->address = $params['address'];
        $shop->latitude = $params['latitude'];
        $shop->longitude = $params['longitude'];
        $shop->province_id = $params['province_id'];
        $shop->city_id = $params['city_id'];
        $shop->district_id = $params['district_id'];
        $shop->street_id = $params['street_id'];
        $shop->description = $params['description'];
        $shop->plan_id = $params['plan_id'];
        if($uploadresult)
            $shop->shop_pic = $uploadresult;
        $shop->shop_pics = $params['shoppics'];
        $shop->save();
        $tagarr = explode(',',$params['tag_ids']);
        if($tagarr && $tagarr[0]){
            foreach ($tagarr AS $value){
                $shoptag = new ShopTag();
                $shoptag->shop_id = $shop->shop_id;
                $shoptag->tag_id = $value;
                $shoptag->save();
            }
        }
        $playarr = explode(',',$params['play_ids']);
        if($playarr && $playarr[0]){
            foreach ($playarr AS $value){
                $shopplay = new ShopPlay();
                $shopplay->shop_id = $shop->shop_id;
                $shopplay->play_id = $value;
                $shopplay->save();
            }
        }
        return true;
    }

    public function getPlayByShop($shop_id){
        return Play::find()
            ->from('{{%play}} p')
            ->leftJoin('{{%shop_play}} sp','p.play_id=sp.play_id')
            ->where("sp.shop_id=$shop_id")
            ->asArray()
            ->all();
    }

    public function editShopById($id, $params, $uploadresult='')
    {
        if(!$shop = Shop::findOne($id)) return false;

        $shop->shop_no = $params['shop_no'];
        $shop->shop_name = $params['shop_name'];
        $shop->shop_parent_name = $params['shop_parent_name'];
        $shop->address = $params['address'];
        $shop->latitude = $params['latitude'];
        $shop->longitude = $params['longitude'];
        $shop->province_id = $params['province_id'];
        $shop->city_id = $params['city_id'];
        $shop->district_id = $params['district_id'];
        $shop->street_id = $params['street_id'];
        $shop->description = $params['description'];
        $shop->plan_id = $params['plan_id'];
        if($uploadresult)
            $shop->shop_pic = $uploadresult;
        $shop->shop_pics = $params['shoppics'];
        $tagarr = explode(',',$params['tag_ids']);
        if($tagarr && $tagarr[0]){
            $oldtag = ShopTag::find()->where(['shop_id'=>$id])->asArray()->all();
            $oldtag = array_column($oldtag,'tag_id');
            $need_del = array_diff($oldtag,$tagarr);
            $need_add = array_diff($tagarr,$oldtag);
            $need_add = array_values($need_add);
            if($need_del){
                foreach ($need_del AS $value){
                    $shoptag = ShopTag::findOne(['shop_id'=>$id,'tag_id'=>$value]);
                    $shoptag->delete();
                }
            }
            if($need_add && isset($need_add[0])){
                foreach ($need_add AS $value1){
                    $shoptag = new ShopTag();
                    $shoptag->shop_id = $id;
                    $shoptag->tag_id = $value1;
                    $shoptag->save();
                }
            }
        }

        $playarr = explode(',',$params['play_ids']);
        if($playarr && $playarr[0]){
            $oldplay = ShopPlay::find()->where(['shop_id'=>$id])->asArray()->all();
            $oldplay = array_column($oldplay,'play_id');
            $need_del = array_diff($oldplay,$playarr);
            $need_add = array_diff($playarr,$oldplay);
            $need_add = array_values($need_add);
            if($need_del){
                foreach ($need_del AS $value2){
                    $shopplay = ShopPlay::findOne(['shop_id'=>$id,'play_id'=>$value2]);
                    $shopplay->delete();
                }
            }
            if($need_add && isset($need_add[0])){
                foreach ($need_add AS $value3){
                    $shopplay = new ShopPlay();
                    $shopplay->shop_id = $id;
                    $shopplay->play_id = $value3;
                    $shopplay->save();
                }
            }
        }

        return $shop->save();
    }

    public function getById($id)
    {
        return Shop::find()->where(['shop_id' => $id])->asArray()->one();
    }

    public function deleteById($id)
    {
        $tag = Tag::findOne($id);
        $tag->delete();
        return true;
    }

    public function saveStatus($id)
    {
        $shop = Shop::findOne($id);
        if($shop->status)
            $shop->status = 0;
        else
            $shop->status = 1;
        return $shop->save();
    }

    public function saveShopTag($shop,$tag){
        $shoptag = ShopTag::findOne(['shop_id'=>$shop,'tag_id'=>$tag]);
        return $shoptag->delete();
    }

    public function getShopListByOwner($user_id){
        return Shop::find()
            ->select('s.*')
            ->from('{{%shop}} s')
            ->where("s.owner_user_id=$user_id")
            ->asArray()
            ->all();
    }

    public function getAllShop(){
        return Shop::find()
            ->where("status=1")
            ->asArray()
            ->all();
    }

    public function getAllShops(){
        return Shop::find()
            ->asArray()
            ->all();
    }

    public function getContract($query = [], $page = 1, $limit = 10){
        $shop = Shop::find()
            ->select("s.*,u.phone as owner_phone")
            ->from('{{%shop}} s')
            ->leftJoin('{{%user}} u','u.user_id=s.owner_user_id')
            ->filterWhere($query)->orderBy('shop_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);

        $lists = $shop->asArray()->all();
        foreach ($lists AS $key=>&$value){
            $manager = Manager::find()
                ->select("m.*,u.phone as phone")
                ->from('{{%manager}} m')
                ->leftJoin('{{%user}} u','u.user_id=m.user_id')
                ->where(['shop_id'=>$value['shop_id']])
                ->asArray()
                ->all();
            $value['manager'] = $manager;
        }
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $shop->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'user/contract',
                'query' => $query
            ]
        ];
        return $return;

    }

    public function addContract($params){
        $shop = Shop::findOne(['shop_id'=>$params['shop_id']]);
        $shop->owner_user_id = $params['user_id'];
        $shop->owner_user_name = $params['name'];
        $shop->contract_start_time = $params['contract_start_time'] . " 00:00:00";
        $shop->contract_end_time = $params['contract_end_time'] . " 23:59:59";
        $shop->contract_create_time = date('Y-m-d H:i:s');
        return $shop->save();
    }

    public function editOwnerContract($id,$params){
        $shop = Shop::findOne($id);
        $shop->owner_user_id = $params['user_id'];
        $shop->owner_user_name = $params['owner_user_name'];
        $shop->contract_start_time = $params['contract_start_time'] . " 00:00:00";
        $shop->contract_end_time = $params['contract_end_time'] . " 23:59:59";
        return $shop->save();
    }

    public function getDeviceByShopId($id, $query=[], $page = 1, $limit = 10){
        if(!$id && $query['shop_id'])
            $id = $query['shop_id'];
        $device = Device::find()
            ->where(['shop_id'=>$id,'is_del'=>0])
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $device->asArray()->all();
        foreach($lists AS $key=>&$value){
            $res = HttpCurl::get('/mafu/event/device/status',['imei'=>$value['device_imei']]);
            $res = json_decode($res,true);
            if($res && isset($res['data']))
                $value['device_status'] = $res['data']['status'];
        }
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $device->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'shop/edit',
                'query'=>['shop_id'=>$id]
            ]
        ];
        return $return;
    }

    public function addDevice($id,$params,$uploadresult=''){
        $device = new Device();
        $device->shop_id = $id;
        $device->device_name = $params['device_name'];
        $device->device_pic = $uploadresult;
        $device->device_imei = $params['device_imei'];
        $device->device_high = $params['device_high'];
        $device->device_low = $params['device_low'];
        $device->device_type = $params['device_type'];
        $device_qrcode = $this->createNo();
        $device3 = Device::findOne(['device_qrcode'=>$device_qrcode]);
        while($device3){
            $device_qrcode = $this->createNo();
            $device3 = Device::findOne(['device_qrcode'=>$device_qrcode]);
        }
        $device->device_qrcode = $device_qrcode;
        $device->device_qrcode_pic = $this->scerweima($device_qrcode);
        $res = HttpCurl::get('/mafu/event/add_device',['imei'=>$params['device_imei'],'cat'=>$params['device_type']]);
        return $device->save();
    }

    public function createNo(){
        return mt_rand(10000000,99999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function scerweima($device_qrcode)
    {
        $wxUtil = new WxUtil();
        $access_token = $wxUtil->getAccessToken();
        $params = json_encode(['scene'=>$device_qrcode,'page'=>'pages/toubi/toubi']);
        $result = HttpCurl::requestPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token",$params);
        if (!$result) {
            return false;
        }
        $rand=rand(10,99).substr(microtime(),2,6).substr(time(),4,6);
        $fileName=$rand;
        file_put_contents("yoyoerweima/".$fileName.".jpeg", $result);
        return "/yoyoerweima/".$fileName.".jpeg";

    }


    public function getDeviceById($id){
        return Device::find()->where(['device_id' => $id])->asArray()->one();
    }

    public function editDeviceById($id, $params,$uploadresult=''){
        $device = Device::findOne($id);
        $device->device_name = $params['device_name'];
        if($uploadresult)
            $device->device_pic = $uploadresult;
        $device->device_imei = $params['device_imei'];
        $device->device_high = $params['device_high'];
        $device->device_low = $params['device_low'];
        $device->device_type = $params['device_type'];
        $res = HttpCurl::get('/mafu/event/add_device',['imei'=>$params['device_imei'],'cat'=>$params['device_type']]);
        return $device->save();
    }

    public function deleteDevice($id){
        $device = Device::findOne($id);
        $device->is_del = 1;
        return $device->save();
    }

    public function downloadCode($device_id){
        $device = Device::findOne(['device_id'=>$device_id]);
        //require_once(__DIR__ .'/../common/phpqrcode.php');
        $value = $device->device_qrcode_pic;                    //二维码内容
        $value1 = substr ( $value , 13  );
//var_dump(__DIR__.'/../web/yoyoerweima/'.$value1);exit;
//设置头信息
        header('Content-Disposition:attachment;filename=' . basename($value1));
        //header('Content-Length:' . filesize($filename));
//读取文件并写入到输出缓冲
        readfile(__DIR__.'/../web/yoyoerweima/'.$value1);

    }


}
